import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { Agent, Team } from "../types";

export interface UserAgent extends Agent {
    earnings: {
        total: number;
        thisMonth: number;
        lastMonth: number;
    };
    usage: {
        totalUsers: number;
        activeUsers: number;
        totalCalls: number;
        thisMonthCalls: number;
    };
    projects: {
        id: string;
        name: string;
        status: "active" | "completed" | "paused";
        createdAt: Date;
    }[];
}

export interface UserTeam extends Team {
    performance: {
        tasksCompleted: number;
        successRate: number;
        totalCost: number;
        lastActivity: Date;
    };
    agents: {
        id: string;
        name: string;
        status: "active" | "idle" | "error";
    }[];
}

export const useUserStore = defineStore("user", () => {
    // State
    const userAgents = ref<UserAgent[]>([]);
    const userTeams = ref<UserTeam[]>([]);
    const isLoading = ref(false);

    // Mock data
    const mockUserAgents: UserAgent[] = [
        {
            id: "user-agent-1",
            name: "智能内容创作助手",
            description:
                "专业的AI内容创作助手，能够生成高质量的文章、社交媒体内容和营销文案",
            category: "writing",
            pricing: {
                model: "paid",
                price: 0.05,
                currency: "USD",
                usageLimit: 1000,
            },
            capabilities: {
                apiCalls: ["OpenAI GPT-4", "Claude-3"],
                thirdPartyLibraries: ["Jinja2", "Requests"],
                knowledgeBase: ["内容创作最佳实践", "SEO优化指南"],
                customConfiguration: {
                    tone: "professional",
                    language: "zh-CN",
                },
            },
            metadata: {
                createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
                updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
                creatorId: "1",
                usageCount: 1250,
                rating: 4.8,
                reviews: [],
                logo: "✍️",
            },
            status: "active",
            earnings: {
                total: 1250.5,
                thisMonth: 320.75,
                lastMonth: 280.25,
            },
            usage: {
                totalUsers: 156,
                activeUsers: 89,
                totalCalls: 12500,
                thisMonthCalls: 3200,
            },
            projects: [
                {
                    id: "proj-1",
                    name: "电商内容营销项目",
                    status: "active",
                    createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
                },
                {
                    id: "proj-2",
                    name: "社交媒体运营",
                    status: "completed",
                    createdAt: new Date(Date.now() - 45 * 24 * 60 * 60 * 1000),
                },
            ],
        },
        {
            id: "user-agent-2",
            name: "数据分析专家",
            description:
                "强大的数据分析AI，能够处理复杂的数据集并提供深入的洞察和可视化报告",
            category: "analysis",
            pricing: {
                model: "paid",
                price: 0.08,
                currency: "USD",
                usageLimit: 500,
            },
            capabilities: {
                apiCalls: ["Pandas API", "Matplotlib API"],
                thirdPartyLibraries: ["NumPy", "Seaborn", "Plotly"],
                knowledgeBase: ["数据分析方法论", "统计学基础"],
                customConfiguration: {
                    chartType: "interactive",
                    exportFormat: "pdf",
                },
            },
            metadata: {
                createdAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000),
                updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
                creatorId: "1",
                usageCount: 890,
                rating: 4.9,
                reviews: [],
                logo: "📊",
            },
            status: "active",
            earnings: {
                total: 890.4,
                thisMonth: 245.6,
                lastMonth: 198.8,
            },
            usage: {
                totalUsers: 98,
                activeUsers: 67,
                totalCalls: 8900,
                thisMonthCalls: 2450,
            },
            projects: [
                {
                    id: "proj-3",
                    name: "销售数据分析",
                    status: "active",
                    createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
                },
            ],
        },
        {
            id: "user-agent-3",
            name: "代码审查助手",
            description:
                "专业的代码审查AI，能够检测代码质量、安全漏洞并提供改进建议",
            category: "coding",
            pricing: {
                model: "freemium",
                price: 0.03,
                currency: "USD",
                usageLimit: 2000,
            },
            capabilities: {
                apiCalls: ["GitHub API", "SonarQube API"],
                thirdPartyLibraries: ["ESLint", "Prettier"],
                knowledgeBase: ["代码质量标准", "安全最佳实践"],
                customConfiguration: {
                    language: "javascript",
                    strictness: "high",
                },
            },
            metadata: {
                createdAt: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000),
                updatedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
                creatorId: "1",
                usageCount: 2100,
                rating: 4.7,
                reviews: [],
                logo: "🔍",
            },
            status: "active",
            earnings: {
                total: 630.0,
                thisMonth: 180.0,
                lastMonth: 165.0,
            },
            usage: {
                totalUsers: 234,
                activeUsers: 156,
                totalCalls: 21000,
                thisMonthCalls: 6000,
            },
            projects: [
                {
                    id: "proj-4",
                    name: "开源项目代码审查",
                    status: "active",
                    createdAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000),
                },
                {
                    id: "proj-5",
                    name: "企业代码质量提升",
                    status: "paused",
                    createdAt: new Date(Date.now() - 50 * 24 * 60 * 60 * 1000),
                },
            ],
        },
    ];

    const mockUserTeams: UserTeam[] = [
        {
            id: "user-team-1",
            name: "电商运营团队",
            description: "专业的电商运营团队，负责产品推广、内容创作和数据分析",
            projectRequirements:
                "需要创建产品描述、社交媒体内容和销售数据分析报告",
            selectedAgents: ["user-agent-1", "user-agent-2"],
            configuration: {
                workflow: [
                    {
                        id: "step-1",
                        name: "内容创作",
                        description: "创建产品描述和营销文案",
                        agentId: "user-agent-1",
                        order: 1,
                        configuration: { tone: "persuasive" },
                    },
                    {
                        id: "step-2",
                        name: "数据分析",
                        description: "分析销售数据和用户行为",
                        agentId: "user-agent-2",
                        order: 2,
                        configuration: { reportType: "comprehensive" },
                    },
                ],
                budget: 500,
                timeline: "30天",
            },
            metadata: {
                createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
                updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
                creatorId: "1",
                status: "active",
            },
            performance: {
                tasksCompleted: 45,
                successRate: 92.5,
                totalCost: 125.5,
                lastActivity: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2 hours ago
            },
            agents: [
                {
                    id: "user-agent-1",
                    name: "智能内容创作助手",
                    status: "active",
                },
                {
                    id: "user-agent-2",
                    name: "数据分析专家",
                    status: "active",
                },
            ],
        },
        {
            id: "user-team-2",
            name: "软件开发团队",
            description: "全栈开发团队，负责代码开发、审查和测试",
            projectRequirements: "开发一个电商网站，包括前端、后端和数据库设计",
            selectedAgents: ["user-agent-3"],
            configuration: {
                workflow: [
                    {
                        id: "step-3",
                        name: "代码审查",
                        description: "审查代码质量和安全性",
                        agentId: "user-agent-3",
                        order: 1,
                        configuration: { language: "javascript" },
                    },
                ],
                budget: 800,
                timeline: "60天",
            },
            metadata: {
                createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
                updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
                creatorId: "1",
                status: "active",
            },
            performance: {
                tasksCompleted: 78,
                successRate: 88.2,
                totalCost: 245.8,
                lastActivity: new Date(Date.now() - 30 * 60 * 1000), // 30 minutes ago
            },
            agents: [
                {
                    id: "user-agent-3",
                    name: "代码审查助手",
                    status: "active",
                },
            ],
        },
    ];

    // Getters
    const totalEarnings = computed(() => {
        return userAgents.value.reduce(
            (sum, agent) => sum + agent.earnings.total,
            0
        );
    });

    const monthlyEarnings = computed(() => {
        return userAgents.value.reduce(
            (sum, agent) => sum + agent.earnings.thisMonth,
            0
        );
    });

    const totalUsers = computed(() => {
        return userAgents.value.reduce(
            (sum, agent) => sum + agent.usage.totalUsers,
            0
        );
    });

    const activeUsers = computed(() => {
        return userAgents.value.reduce(
            (sum, agent) => sum + agent.usage.activeUsers,
            0
        );
    });

    const totalTasksCompleted = computed(() => {
        return userTeams.value.reduce(
            (sum, team) => sum + team.performance.tasksCompleted,
            0
        );
    });

    const averageSuccessRate = computed(() => {
        if (userTeams.value.length === 0) return 0;
        const totalRate = userTeams.value.reduce(
            (sum, team) => sum + team.performance.successRate,
            0
        );
        return totalRate / userTeams.value.length;
    });

    // Actions
    const fetchUserAgents = async () => {
        isLoading.value = true;
        try {
            // TODO: Implement actual API call
            await new Promise((resolve) => setTimeout(resolve, 500)); // Simulate API call
            userAgents.value = mockUserAgents;
        } catch (error) {
            console.error("Error fetching user agents:", error);
        } finally {
            isLoading.value = false;
        }
    };

    const fetchUserTeams = async () => {
        isLoading.value = true;
        try {
            // TODO: Implement actual API call
            await new Promise((resolve) => setTimeout(resolve, 500)); // Simulate API call
            userTeams.value = mockUserTeams;
        } catch (error) {
            console.error("Error fetching user teams:", error);
        } finally {
            isLoading.value = false;
        }
    };

    const getAgentById = (id: string) => {
        return userAgents.value.find((agent) => agent.id === id);
    };

    const getTeamById = (id: string) => {
        return userTeams.value.find((team) => team.id === id);
    };

    return {
        // State
        userAgents,
        userTeams,
        isLoading,
        // Getters
        totalEarnings,
        monthlyEarnings,
        totalUsers,
        activeUsers,
        totalTasksCompleted,
        averageSuccessRate,
        // Actions
        fetchUserAgents,
        fetchUserTeams,
        getAgentById,
        getTeamById,
    };
});
